package com.supermarket.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.supermarket.common.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 * 用于验证用户是否已经登录
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从session中获取用户信息
        HttpSession session = request.getSession();
        Object user = session.getAttribute("currentUser");
        
        // 如果用户未登录，返回错误响应
        if (user == null) {
            // 设置响应状态码和内容类型
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            
            // 返回JSON格式的错误信息
            ResponseResult<String> result = ResponseResult.error(401, "请先登录");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }
        
        // 用户已登录，放行请求
        return true;
    }
} 